<?php

namespace addons\fzdc\controller;

use addons\fzdc\library\Wxlogin;
use app\admin\model\fzdc\coupon\Receive;
use app\admin\model\fzdc\goods\Goods;
use app\admin\model\fzdc\order\Cart;
use app\admin\model\fzdc\pact\Pact;
use app\admin\model\fzdc\store\StoreCollect;
use app\admin\model\fzdc\Userdetail;
use app\admin\model\fzdc\Third;
use app\common\controller\Api;
use app\admin\model\User as U;
use app\admin\model\fzdc\Signin;
use app\common\model\ScoreLog;
use think\Log;
use think\Request;
use think\Validate;
use app\admin\model\fzdc\distribution\Share;

class User extends Api
{

    protected $noNeedLogin = ['login', 'pact','wx_login'];
    protected $noNeedRight = ['*'];

    public function __construct(Request $request = null)
    {
        $this->config = get_addon_config("fzdc");
        parent::__construct($request);
    }

    /*
     * 注册/登录
     */
    public function login()
    {
        $encryptdata = $this->request->post('encryptedData', '', 'trim');
        $iv = $this->request->post('iv');
        $code = $this->request->post('code');
        $parent_id = $this->request->header("pid") ?? 0;
        if (empty($code) || !$encryptdata || !$iv) {
            $this->error('请求数据不能为空');
        }
        Log::info("上级用户id:" . $parent_id);
        $res = \app\admin\model\User::get($parent_id);
        if (!$res && $parent_id != 0) {
            $this->error('不存在此用户');
        }
        $iv = urldecode($iv);
        $encryptdata = urldecode($encryptdata);
        //微信授权登录
        $login = new Wxlogin();
        $res = $login->login($code, $encryptdata, $iv);
        if (!$res["code"]) {
            $this->error($res['msg']);
        }
        $openId = $res['data']['openid'];
        $mobile = $res['data']['mobile'];
        //查询用户表是否存在此open_id,存在则登录,不存在则注册
        $user = Userdetail::get(["openid" => $openId]);
        if ($user){
            $u = U::get($user->user_id);
        }else{
            $u = false;
        }
        if ($user && $u) {
            //登录
            $u_info = U::get($user->user_id);
            if ($u_info['status'] != "normal") {
                $this->error("用户状态不正确");
            }
            //查询该用户是否有上级
            if ($user->parent_id == 0 && $parent_id) {
                $user->parent_id = $parent_id;
                $user->save();
                //添加分享邀请信息
                $pname = \app\common\model\User::where("id", $parent_id)->value("username");
                Share::create([
                    "user_id" => $user['id'],
                    "p_id" => $parent_id,
                    "desc" => $u_info['username'] . "在" . date("Y-m-d H:i:s") . "成为" . $pname . "下级",
                    "createtime" => time(),
                ]);
            }
            $ret = $this->auth->direct($user->user_id);
            if ($ret) {
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success("登录成功", $data);
            } else {
                $this->error($this->auth->getError());
            }
        } else {
            //注册
            $username = "微信用户" . chr(rand(65, 90)) . chr(rand(97, 122)) . chr(rand(65, 90)) . chr(rand(97, 122)) . substr($mobile, -4);
            $password = mt_rand(100000, 999999);
            //判断用户是否用手机号注册过 如果注册过 绑定微信号
            $info = U::get(["mobile" => $mobile]);
            if ($info) {
                if ($info['status'] != "normal") {
                    $this->error("用户状态不正确");
                }
                //更新用户表中的openid
                $detail_res = Userdetail::get(["user_id" => $info->id]);
                if ($detail_res) {
                    if ($detail_res->parent_id == 0 && $parent_id) {
                        $detail_res->parent_id = $parent_id;
                        $detail_res->save();
                        //添加分享邀请信息
                        $pname = \app\common\model\User::where("id", $parent_id)->value("username");
                        Share::create([
                            "user_id" => $info['id'],
                            "p_id" => $parent_id,
                            "desc" => $info['username'] . "在" . date("Y-m-d H:i:s") . "通过" . $pname . "注册",
                            "createtime" => time(),
                        ]);
                    }
                    Userdetail::update(["openid" => $openId], ["user_id" => $info->id]);
                } else {
                    if (!$parent_id) {
                        $parent_id = 0;
                    }
                    Userdetail::create([
                        'openid' => $openId,
                        'user_id' => $info->id,
                        'parent_id' => $parent_id,
                        'createtime' => time(),
                        'updatetime' => time(),
                    ]);
                }
                //第三方登录表插入数据
                Third::create([
                    "user_id" => $info->id,
                    "platform" => 'wechat',
                    "apptype" => 'miniapp',
                    "openid" => $openId,
                    "createtime" => time(),
                ]);
                $this->auth->direct($info->id);
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success("登录成功", $data);
            } else {
                $ret = $this->auth->register($username, $password, "", $mobile, []);
                if ($ret) {
                    $user = U::get($this->auth->id);
                    $user->avatar = "/assets/img/avatar.png";
                    $user->save();
                    if (!$parent_id) {
                        $parent_id = 0;
                    }
                    $detail = [
                        'openid' => $openId,
                        'user_id' => $user->id,
                        'parent_id' => $parent_id,
                        'createtime' => time(),
                        'updatetime' => time(),
                    ];
                    Userdetail::create($detail);

                    Third::create([
                        "user_id" => $user->id,
                        "platform" => 'wechat',
                        "apptype" => 'miniapp',
                        "openid" => $openId,
                        "createtime" => time(),
                    ]);

                    $data = ['userinfo' => $this->auth->getUserinfo()];
                    $this->success(__('注册成功'), $data);
                } else {
                    $this->error($this->auth->getError());
                }
            }
        }
    }

    /*
     * 授权登录
     */
    public function wx_login(){
        $username = $this->request->post('username');
        $avatar = $this->request->post('avatar');
        $code = $this->request->post('code');
        $parent_id = $this->request->header("pid") ?? 0;
        if (empty($username)) {
            $this->error('昵称不能为空');
        }
        if (empty($avatar)) {
            $this->error('头像不能为空');
        }
        if (empty($code)) {
            $this->error('code不能为空');
        }
        //微信授权登录
        $login = new Wxlogin();
        $res = $login->get_openid($code);
        if (!$res["code"]) {
            $this->error($res['msg']);
        }

        $openId = $res['data']['openid'];

        //查询用户表是否存在此open_id,存在则登录,不存在则注册
        $user = Userdetail::get(["openid" => $openId]);
        if ($user) {
            //登录
            $u_info = U::get($user->user_id);
            if ($u_info['status'] != "normal") {
                $this->error("用户状态不正确");
            }

            //查询该用户是否有上级
            if ($user->parent_id == 0 && $parent_id) {
                $user->parent_id = $parent_id;
                $user->save();
                //添加分享邀请信息
                $pname = \app\common\model\User::where("id", $parent_id)->value("username");
                Share::create([
                    "user_id" => $user['id'],
                    "p_id" => $parent_id,
                    "desc" => $u_info['username'] . "在" . date("Y-m-d H:i:s") . "成为" . $pname . "下级",
                    "createtime" => time(),
                ]);
            }
            $ret = $this->auth->direct($user->user_id);
            if ($ret) {
                $u_info->avatar = $avatar;
                $u_info->username = $username;
                $u_info->save();
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success("登录成功", $data);
            } else {
                $this->error($this->auth->getError());
            }
        } else {
            //注册
            $password = mt_rand(100000, 999999);
            $ret = $this->auth->register($username, $password, "", "", []);
            if ($ret) {
                $user = U::get($this->auth->id);
                $user->avatar = $avatar;
                $user->save();
                if (!$parent_id) {
                    $parent_id = 0;
                }
                $detail = [
                    'openid' => $openId,
                    'user_id' => $user->id,
                    'parent_id' => $parent_id,
                    'createtime' => time(),
                    'updatetime' => time(),
                ];
                Userdetail::create($detail);

                Third::create([
                    "user_id" => $user->id,
                    "platform" => 'wechat',
                    "apptype" => 'miniapp',
                    "openid" => $openId,
                    "createtime" => time(),
                ]);

                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success(__('注册成功'), $data);
            } else {
                $this->error($this->auth->getError());
            }

        }
    }

    /*
    * 获取会员个人信息
    */
    public function userInfo()
    {
        $user = $this->auth->id;
        $data = U::where("id", $user)->field("id,username,mobile,avatar,score,level,money,email,birthday,gender")->find();
        $detail = Userdetail::where(["user_id" => $user])->field("openid,login_flag,code")->find();
        if (!$detail){
            Userdetail::create([
                'user_id' => $user,
                'createtime' => time(),
                'updatetime' => time(),
            ]);
            $detail = Userdetail::where(["user_id" => $user])->field("openid,login_flag,code")->find();
        }
        $data['openid'] = $detail['openid'];
        $data['login_flag'] = $detail['login_flag'];
        $data['code'] = $detail['code'];
        //获取下一级所需积分
        $upgrade = $this->config['upgrade'];
        if (isset($upgrade[$data['level'] + 1])) {
            $level = $data['level'] + 1;
            $data['upgrade'] = $upgrade[$level];
        } else {
            $data['upgrade'] = 0;
        }
        $data['avatar'] = cdnurl($data['avatar'], true);
        //获取上一次购物车
        $res = Cart::where(["user_id" => $user])->order("id", "desc")->find();
        if ($res) {
            $type = Goods::get($res['goods_id']);
            if ($type){
                if ($type['shipment'] == 3) {
                    $data['type'] = 2;
                } else {
                    $data['type'] = $type['shipment'];
                }
            }else{
                $data['type'] = 2;
            }

        } else {
            $data['type'] = 2;
        }
        //判断该用户关联的店铺
        $res = \app\admin\model\fzdc\store\User::where(["user_id" => $user])->find();
        $data['store_user'] = 1;
        if (!$res) {
              $res2 = \app\admin\model\Merchant::where(["user_id" => $user])->find();
            if(empty($res2)){
                $data['store_user'] = 0;
            }else{
                $data['store_user'] = 1;
            }
            // $data['store_user'] = 0;
        }
        //判断是否有未支付的订单
        $res = \app\admin\model\fzdc\order\Order::where(["user_id" => $user, "status" => 1,'type'=>1])->find();
        if ($res) {
            $data['order_num'] = 1;
        } else {
            $data['order_num'] = 0;
        }
        
            $data['coupon_num'] = 1;
        //查询优惠券数量
        $data['coupon_num'] = Receive::where(["user_id" => $user, "state" => 0])->count();


        $this->success("获取成功", $data);
    }

    /*
     * 修改会员个人信息
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $mobile = $this->request->post('mobile');
        $birthday = $this->request->post('birthday');
        $gender = $this->request->post('gender');
        $file = $this->request->post('file');

        if (empty($username)) {
            $this->error("用户名不能为空");
        }
        if (empty($mobile)) {
            $this->error("手机号不能为空");
        }
        if (empty($birthday)) {
            $this->error("生日不能为空");
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error("手机号不符合规则");
        }
        if ($username) {

            $user->username = $username;
        }
        $user->avatar = $file;
        $user->username = $username;
        $user->mobile = $mobile;
        $user->birthday = $birthday;
        $user->gender = $gender;
        $user->save();
        $this->success("修改成功");
    }

    /*
     * 收藏列表
     */
    public function collectionList()
    {
        $userId = $this->auth->id;
        $list = StoreCollect::with(["store"])->where("user_id", $userId)->field("id,lesson_id,flag")->select();


        $this->success("成功", $list);
    }

    /*
     * 取消收藏
     */
    public function cancelCollection()
    {
        $userId = $this->auth->id;
        $id = $this->request->post('id');
        if (!$id) {
            $this->error("缺少必填参数");
        }
        StoreCollect::destroy(["user_id" => $userId, "store_id" => $id]);
        $this->success("取消收藏成功");
    }

    /*
     * 手机号绑定微信账号
     */
    public function binding()
    {
        $userId = $this->auth->id;
        $code = $this->request->post('code');
        //查询该用户是否已绑定
        $user = Userdetail::get(["user_id" => $userId]);
        if (!empty($user['openid'])) {
            $this->error("已绑定，无需重复绑定");
        }
        if (empty($code)) {
            $this->error('code不能为空');
        }
        //微信授权登录
        $login = new Wxlogin();
        $res = $login->get_openid($code);
        if (!$res["code"]) {
            $this->error($res['msg']);
        }

        $openId = $res['data']['openid'];
        //更新用户表中的openid
        $user->openid = $openId;
        $user->save();
        //第三方登录表插入数据
        Third::create([
            "user_id" => $userId,
            "platform" => 'wechat',
            "apptype" => 'miniapp',
            "openid" => $openId,
            "createtime" => time(),
        ]);
        $this->success("绑定成功");
    }

    /*
     * 解除微信绑定
     */
    public function remove()
    {
        $userId = $this->auth->id;
        //查询该用户是否已绑定
        $user = Userdetail::get(["user_id" => $userId]);
        if (empty($user['openid'])) {
            $this->error("还未绑定微信账号");
        }
        $user->openid = "";
        $user->save();
        Third::destroy(["user_id" => $userId]);
        $this->success("解绑成功");
    }

    /*
     * 获取会员码
     */
    public function code()
    {
        $user = $this->auth->id;
        //首先查询数据库中有没有会员码
        $info = U::where("id", $user)->find();
        $detail = Userdetail::get(["user_id" => $user]);
//        var_dump(ROOT_PATH."addons/fzdc/library/phpqrcode/phpqrcode.php");die;
        include ROOT_PATH . "addons/fzdc/library/phpqrcode/phpqrcode.php";
        if (empty($detail['code'])) {
            $data = json_encode([
                "user_id" => $info['id'],
            ]);

            $img = '/uploads/fzdc/' . time() . rand(0, 999);
            //生成二维码图片
            $errorCorrectionLevel = 'L';    //容错级别
            $matrixPointSize = 5;            //生成图片大小
            $img = md5($img) . '.png';
            $file_path = ROOT_PATH . config('template.tpl_replace_string.__FILE_UPLOAD_PATH__') . 'public/uploads/' . 'fzdc/';
            $path = $file_path;

            if (!file_exists($path)) {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($path, 0777, true);
            }
            $filename = $path . $img;

            \QRcode::png($data, $filename, $errorCorrectionLevel, $matrixPointSize, 2);

            $QR = $filename;                //已经生成的原始二维码图片文件
            $QR = imagecreatefromstring(file_get_contents($QR));
            //保存图片,销毁图形，释放内存
            if (!file_exists($filename)) {
                imagepng($QR, $filename);
                imagedestroy($QR);
            } else {
                imagedestroy($QR);
            }
            //存储到会员表
            $detail->code = "/uploads/fzdc/" . $img;
            $detail->updatetime = time();
            $detail->save();
//            U::update(["code"=>"/uploads/fzdc/".$img,"updatetime"=>time()],["id"=>$user]);
            $this->success("成功", request()->domain() . "/uploads/fzdc/" . $img);
        } else {
            //判断是否超过三十秒
            if (bcsub(time(), $detail['updatetime']) > 30) {
                $data = json_encode([
                    "user_id" => $info['id'],
                ]);

                $img = '/uploads/fzdc/' . time() . rand(0, 999);
                //生成二维码图片
                $errorCorrectionLevel = 'L';    //容错级别
                $matrixPointSize = 5;            //生成图片大小
                $img = md5($img) . '.png';
                $file_path = ROOT_PATH . config('template.tpl_replace_string.__FILE_UPLOAD_PATH__') . 'public/uploads/' . 'fzdc/';
                $path = $file_path;

                if (!file_exists($path)) {
                    //检查是否有该文件夹，如果没有就创建，并给予最高权限
                    mkdir($path, 0777, true);
                }
                $filename = $path . $img;
                \QRcode::png($data, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
                $QR = $filename;                //已经生成的原始二维码图片文件
                $QR = imagecreatefromstring(file_get_contents($QR));
                //保存图片,销毁图形，释放内存
                if (!file_exists($filename)) {
                    imagepng($QR, $filename);
                    imagedestroy($QR);
                } else {
                    imagedestroy($QR);
                }
                //存储到会员表
                $detail->code = "/uploads/fzdc/" . $img;
                $detail->updatetime = time();
                $detail->save();
//                U::update(["code"=>"/uploads/fzdc/".$img,"updatetime"=>time()],["id"=>$user]);
                $this->success("成功", request()->domain() . "/uploads/fzdc/" . $img);
            } else {
                $this->success("成功", request()->domain() . $detail['code']);
            }
        }

    }

    /*
     * 修改订阅
     */
    public function subscribe()
    {
        $user = $this->auth->id;
        $switch = $this->request->post('switch'); //0关1开
        if (!in_array($switch, [0, 1])) {
            $this->error("参数错误");
        }
        Userdetail::update(["subscribe" => $switch], ["user_id" => $user]);
        $this->success("修改成功");
    }

    /*
     * 获取会员协议
     */
    public function pact()
    {
        $id = $this->request->post("name");
        if (!$id) {
            $this->error("缺少参数");
        }
        $res = Pact::get(["title" => $id]);
        if (!$res) {
            $this->error("协议不存在");
        }
        $this->success("成功", $res);

    }

    /*
     * 消息通知列表
     */
    public function message()
    {
        $page = $this->request->post('page') ?? 1;  //页码
        $limit = $this->request->post('limit') ?? 10; //每页显示条数
        $data = \app\admin\model\fzdc\notice\Notice::field("id,title,image,content,description,createtime")->paginate(["page" => $page, "list_rows" => $limit])
            ->each(function ($item) {
                $item->image = cdnurl($item->image, true);
            });
        $this->success("成功", $data);
    }

    /*
     * 消息通知详情
     */
    public function message_detail()
    {
        $id = $this->request->post('id');
        if (empty($id)) {
            $this->error("缺少id");
        }
        $data = \app\admin\model\fzdc\notice\Notice::get($id);
        $data['image'] = cdnurl($data['image'], true);
        $this->success("成功", $data);
    }

    /*
     * 签到
     */
    public function signin()
    {
        $user_id = $this->auth->id;
        $time = time() + 3600 * 300;
        $user = U::find($user_id);
        $detail = U::find(["user_id" => $user_id]);
        //判断是否签到过
        $info = \app\admin\model\fzdc\Signin::where("user_id", $user_id)->order("id", "desc")->find();
        if ($info) {
            $flag = false;
            if ($info->last_time == '') {
                //判断当天是否签到过
                $time1 = date("Y-m-d", $time);
                $time2 = date("Y-m-d", $info->time);
                $Date_time1 = explode("-", $time1);
                $Date_time2 = explode("-", $time2);
                if ($Date_time1[1] == $Date_time2[1] && $Date_time1[2] == $Date_time2[2]) {
                    $this->success("今天已签到，明天再来吧");
                } else {
                    //判断是否连续
                    if (($Date_time1[0] == $Date_time2[0] && $Date_time1[1] == $Date_time2[1])) {
                        if ($Date_time1[2] - $Date_time2[2] > 1) {
                            $points = $this->config['points'];
                            $day = 1;
                        } else {
                            $points = bcadd($this->config['points'], $this->config['addup']);
                            $day = 2;
                            $flag = true;
                        }
                    } else {
                        $points = $this->config['points'];
                        $day = 1;
                    }
                }

            } else {
                //判断当天是否签到过
                $time1 = date("Y-m-d", $time);
                $time2 = date("Y-m-d", $info->time);
                $Date_time1 = explode("-", $time1);
                $Date_time2 = explode("-", $time2);
                if ($Date_time1[1] == $Date_time2[1] && $Date_time1[2] == $Date_time2[2]) {
                    $this->success("今天已签到，明天再来吧");
                }
                //判断签到是否中断
                if (($Date_time1[0] == $Date_time2[0] && $Date_time1[1] == $Date_time2[1])) {
                    if ($Date_time1[2] - $Date_time2[2] > 1) {
                        $points = $this->config['points'];
                        $day = 1;
                    } else {
                        if ($detail->signins > $this->config['max']) {
                            $points = $info->points;
                            $day = $detail->signins;
                        } else {
                            $points = $info->points + $this->config['addup'];
                            $day = $detail->signins;
                        }
                        $flag = true;
                    }
                } else {
                    $points = $this->config['points'];
                    $day = 1;
                }
            }
            //赠送积分
            Signin::create([
                "user_id" => $user_id,
                "time" => $time,
                "last_time" => $info->time,
                "points" => $points
            ]);
            $user->score = $user->score + $this->config['points'];
            if ($flag == true) {
                $detail->signins = $detail->signins + 1;
            } else {
                $detail->signins = 1;
            }
            $user->save();
            $detail->save();
            $before = $user->score;
            $after = $user->score + $this->config['points'];
            $memo = "累计签到" . $day . "天,赠送" . $points . "积分";
            //写入日志
            ScoreLog::create(['user_id' => $user_id, 'score' => $this->config['points'], 'before' => $before, 'after' => $after, 'memo' => $memo]);
            //更新连续签到天数

            $this->success("签到成功");
        } else {
            //赠送积分
            Signin::create([
                "user_id" => $user_id,
                "time" => $time,
                "last_time" => "",
                "points" => $this->config['points']
            ]);
            $user = U::find($user_id);
            $user->score = $user->score + $this->config['points'];
            $user->save();
            $before = $user->score;
            $after = $user->score + $this->config['points'];
            $memo = "累计签到1天,赠送" . $this->config['points'] . "积分";
            //写入日志
            ScoreLog::create(['user_id' => $user_id, 'score' => $this->config['points'], 'before' => $before, 'after' => $after, 'memo' => $memo]);
            $this->success("签到成功");
        }
    }

    /*
     * 退出登录
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error("请求方法异常");
        }
        $this->auth->logout();
        $this->success("退出登录成功");
    }

}
